import json
import base64
import random
import requests
import string
import pymysql
from concurrent.futures import ThreadPoolExecutor
from CodeOCR import Chaojiying_Client

"""
批量注册海角账号
如果注册成功则写成txt文件
"""


class HJJT:
    def __init__(self):
        self.__domain = "https://www.hj87d29.top"
        self.OcrCode = Chaojiying_Client('19924454082', 'dzyDZY12@', '959141')
        self.conn = pymysql.connect(host='localhost', user='root', password='123456', db='haijiaouser', port=3306)
        self.cursor = self.conn.cursor()
        self.r_num = 0
        self.proxy = {
            "http:": "218.91.141.192:64256",
            "https:": "218.91.141.192:64256",
        }

    # ua池
    def get_ua(self):
        user_agents = [
            'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36 OPR/26.0.1656.60',
            'Opera/8.0 (Windows NT 5.1; U; en)',
            'Mozilla/5.0 (Windows NT 5.1; U; en; rv:1.8.1) Gecko/20061208 Firefox/2.0.0 Opera 9.50',
            'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; en) Opera 9.50',
            'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0',
            'Mozilla/5.0 (X11; U; Linux x86_64; zh-CN; rv:1.9.2.10) Gecko/20100922 Ubuntu/10.10 (maverick) Firefox/3.6.10',
            'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.57.2 (KHTML, like Gecko) Version/5.1.7 Safari/534.57.2 ',
            'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36',
            'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
            'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.133 Safari/534.16',
            'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36',
            'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko',
            'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.11 TaoBrowser/2.0 Safari/536.11',
            'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.71 Safari/537.1 LBBROWSER',
            'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E)',
            'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.84 Safari/535.11 SE 2.X MetaSr 1.0',
            'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; SV1; QQDownload 732; .NET4.0C; .NET4.0E; SE 2.X MetaSr 1.0) ',
        ]
        user_agent = random.choice(user_agents)  # random.choice(),从列表中随机抽取一个对象
        headers = {'User-Agent': user_agent}
        return headers

    # 海角加密
    def __HaiJiaoJieMa(self, JMFN):
        base64_encoded_string = JMFN
        for i in range(3):
            base64_encoded_string = base64.b64decode(base64_encoded_string)
        # 将解码后的字节对象转换为字符串
        # decoded_string = base64_encoded_string.decode("utf-8")
        return json.loads(base64_encoded_string)

    # 请求验证码图片和id
    def __GetCode(self):
        url = "https://www.hj87d29.top/api/captcha/request?t=signupCaptcha"
        response = requests.get(url, headers=self.get_ua()).json()['data']
        response = self.__HaiJiaoJieMa(response)
        # {'captchaId': 'QLd3xNDeEBS96BujJpMn', 'captchaUrl': '/api/captcha/show?captchaId=QLd3xNDeEBS96BujJpMn&r=1aaf2f92c7264743a0a505ad6b1213e9', 'isCaptcha': True}
        resurl = {
            "captchaUrl": self.__domain + response['captchaUrl'],
            "captchaId": response['captchaId']
        }
        return resurl

    # 识别验证码
    def __OCRCode(self, ImgData):
        res = self.OcrCode.PostPic(ImgData, 4007)
        return res['pic_str']

    # 验证码数据
    def __GetImgB(self, Url):
        response = requests.get(url=Url, headers=self.get_ua()).content
        # with open('./code.png', 'wb') as e:
        #     e.write(response)
        return response

    # 注册
    def __register(self, Udata):
        url = self.__domain + "/api/login/signup"
        jsondata = {
            "CaptchaCode": Udata['CaptchaCode'],
            "CaptchaId": Udata['CaptchaId'],
            "Email": Udata['Email'],
            "Password": "qwe12345",
            "RPassword": "qwe12345",
            "Ref": "",
            "Username": Udata['Username']
        }

        response = requests.post(url=url, headers=self.get_ua(), json=jsondata, proxies=self.proxy).json()

        try:
            res = self.__HaiJiaoJieMa(response['data'])
            return res
        except Exception as e:
            print(f"注册失败, 原因: {response}", e)
            return None

    # 持久化存储
    def __openSQL(self, Data):
        try:
            sql = "INSERT INTO `haijiaouser`.`user` (`token`, `user_id`, `nickname`, `user_email`, `createTime`, `user_name`) VALUES ('%s', '%s', '%s', '%s', '%s', '%s')" % (
                Data['token'], Data['user_id'],
                Data['nickname'], Data['user_email'],
                Data['createTime'], Data['user_name']
            )

            self.cursor.execute(sql)
            self.conn.commit()
            self.r_num += 1
            print(f"用户名: {Data['user_name']}-------------------已成功注册了 {self.r_num} 个账号")
        except Exception as e:
            print("提交到数据库出错", e)

    # 提取账号
    # 提取邮箱
    # 提取用户名
    def __generate_username(self):
        # 生成5到12位长度的用户名，且必须以字母开头
        length = random.randint(5, 6)
        username = random.choice(string.ascii_lowercase)
        allowed_chars = string.ascii_letters + string.digits + '_-'
        for _ in range(length - 1):
            username += random.choice(allowed_chars)

        return "YYy1" + username

    def __generate_email(self, username):
        # 生成10位数以内的邮箱前缀
        length = random.randint(1, 10)

        # 随机生成邮箱后缀
        email_domains = ['@qq.com', '@163.com', '@gmail.com', '@yahoo.com', '@hotmail.com', '@yy.com']
        email_domain = random.choice(email_domains)

        email = username + email_domain
        return email

    # 批量注册
    def piliangzhuc(self):
        user_name = self.__generate_username()
        user_email = self.__generate_email(user_name)
        # 获取验证码的消息
        ImgDta = self.__GetCode()
        BaseData = self.__GetImgB(Url=ImgDta['captchaUrl'])
        code = self.__OCRCode(ImgData=BaseData)
        obj = {
            "CaptchaCode": code,
            "CaptchaId": ImgDta['captchaId'],
            "Email": user_email,
            "Password": "qwe12345",
            "RPassword": "qwe12345",
            "Ref": "",
            "Username": user_name
        }
        response = self.__register(Udata=obj)
        if response is not None:
            Params = {
                "token": response['token'],
                "user_id": response['user']['id'],
                "nickname": response['user']['nickname'],
                "user_email": response['user']['email'],
                "createTime": response['user']['createTime'],
                "user_name": response['user']['username']
            }
            self.__openSQL(Data=Params)

    # 点赞功能
    def dianzhan(self, TzID, token, user_id):
        url = self.__domain + f"/api/topic/like/{TzID}"
        params = self.get_ua()
        params['X-User-Id'] = user_id
        params['X-User-Token'] = token
        res = requests.post(url, headers=params).json()
        dat = res['data']
        if dat is None:
            dat = res['message']
            return dat

        return self.__HaiJiaoJieMa(dat)

    # 收藏功能
    def Shochang(self, Pid, user_id, token, AD):
        # 获取默认收藏夹id
        url = self.__domain + "/api/favorite/v2/folderList"
        params = self.get_ua()
        params['X-User-Id'] = user_id
        params['X-User-Token'] = token
        folderId = self.__HaiJiaoJieMa(requests.get(url=url, headers=params).json()['data'])[0]['id']
        if AD is True:
            url = self.__domain + "/api/favorite/v2/add"
            jsdata = {
                "entityType": "topic",
                "folderId": folderId,
                "entityId": Pid
            }
            res = requests.get(url, headers=params, params=jsdata).json()['success']
            if res:
                return "收藏成功"
        else:
            url = self.__domain + "/api/favorite/v2/delete"
            jsdata = {
                "entityType": "topic",
                "entityIds": Pid
            }
            res = requests.get(url, headers=params, params=jsdata).json()['success']
            if res:
                return "取消收藏成功"

    # 关注
    def guanzhu(self, targetId, user_id, token):
        url = self.__domain + "/api/user/favorite"
        params = self.get_ua()
        params['X-User-Id'] = user_id
        params['X-User-Token'] = token
        folderId = self.__HaiJiaoJieMa(requests.get(url=url, headers=params).json()['data'])[0]['id']
        paramss = {
            "targetId": folderId,
            "opt": "add"
        }
        res = requests.get(url, headers=params, params=paramss).json()
        print(res)

    # 签到
    def qiandao(self):
        headers = {
            'accept': 'application/json, text/plain, */*',
            'accept-language': 'zh-CN,zh;q=0.9',
            'access-control-allow-credentials': 'true',
            'cache-control': 'no-cache',
            # 'content-length': '0',
            'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'contenttype': 'application/json',
            # 'cookie': '_ga=GA1.1.729325568.1713234763; user=%7B%22id%22%3A171315720201%2C%22nickname%22%3A%22%u6D77%u89D2_171315720201%22%2C%22avatar%22%3A%2254%22%2C%22description%22%3A%22%u6D77%u89D2%u793E%u533A%u5185%u5BB9%u5F88%u68D2%uFF0C%u795D%u6D77%u89D2%u793E%u533A%u8D8A%u529E%u8D8A%u597D%u3002%22%2C%22topicCount%22%3A0%2C%22videoCount%22%3A0%2C%22commentCount%22%3A0%2C%22fansCount%22%3A1%2C%22favoriteCount%22%3A0%2C%22status%22%3A0%2C%22sex%22%3A0%2C%22vip%22%3A0%2C%22vipExpiresTime%22%3A%220001-01-01%2000%3A00%3A00%22%2C%22certified%22%3Afalse%2C%22certVideo%22%3Afalse%2C%22certProfessor%22%3Afalse%2C%22famous%22%3Afalse%2C%22forbidden%22%3Afalse%2C%22tags%22%3Anull%2C%22role%22%3A0%2C%22diamondConsume%22%3A0%2C%22title%22%3A%7B%22id%22%3A0%2C%22name%22%3A%22%22%2C%22consume%22%3A0%2C%22consumeEnd%22%3A0%2C%22icon%22%3A%22%22%7D%2C%22friendStatus%22%3Afalse%2C%22voiceStatus%22%3Afalse%2C%22videoStatus%22%3Afalse%2C%22voiceMoneyType%22%3A0%2C%22voiceAmount%22%3A0%2C%22videoMoneyType%22%3A0%2C%22videoAmount%22%3A0%2C%22depositMoney%22%3A0%2C%22phone%22%3A%22%22%2C%22userBank%22%3Anull%2C%22parentId%22%3A0%2C%22gold%22%3A0%2C%22diamond%22%3A0%2C%22passwordSet%22%3Atrue%2C%22payPasswordSet%22%3Afalse%2C%22popularity%22%3A10%2C%22topicLikeNum%22%3A0%2C%22bindUser%22%3A%22%22%2C%22username%22%3A%22yYash_aG2_%22%2C%22email%22%3A%22wasjaY12@wsw.com%22%2C%22emailVerified%22%3Afalse%2C%22createTime%22%3A%222024-04-15%2013%3A00%3A02%22%2C%22lastLoginTime%22%3A%222024-04-16%2010%3A47%3A40%22%2C%22lastLoginIp%22%3A%2214.23.38.53%22%2C%22certifiedExpired%22%3Afalse%2C%22certProfessorExpired%22%3Afalse%2C%22certVideoExpired%22%3Afalse%2C%22hasGaEnabled%22%3Afalse%7D; mainshow=true; token=b386fbd7dd4d48d3b24cc1a41b39e0b9; uid=171316155701; _ga_H4G4E5X3FL=GS1.1.1713292512.6.1.1713294581.0.0.0',
            'mver': '211112203214',
            'origin': 'https://hj2404aa05.top',
            'pragma': 'no-cache',
            'referer': 'https://hj2404aa05.top/task',
            'sec-fetch-dest': 'empty',
            'sec-fetch-mode': 'cors',
            'sec-fetch-site': 'same-origin',
            'user-agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1',
            'x-user-id': '171316155701',
            'x-user-token': 'b386fbd7dd4d48d3b24cc1a41b39e0b9',
        }
        url = self.__domain + "/api/user/user_sign_in"
        res = requests.post(url, headers=headers).json()
        print(res)


if __name__ == '__main__':
    sp = HJJT()
    print(sp.qiandao())
